package com.aaa.controller;

import com.aaa.entity.SysPermission;
import com.aaa.service.SysPermissionService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.ApiController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单权限表(SysPermission)表控制层
 *
 * @author makejava
 * @since 2025-05-07 10:27:01
 */
@RestController
@RequestMapping("/sys/sysPermission")
public class SysPermissionController extends ApiController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @RequestMapping("/getAllList")
    public List<SysPermission> getAllList(){
        List<SysPermission> list = sysPermissionService.list(new LambdaUpdateWrapper<SysPermission>()
                .eq(SysPermission::getDelFlag, 0)
                .eq(SysPermission::getStatus, 1));
        Map<String, List<SysPermission>> parentIdListMap = list.stream().filter(s-> StringUtils.isNotBlank(s.getParentId())).collect(Collectors.groupingBy(SysPermission::getParentId));
        list.forEach(s->s.setChildrenList(parentIdListMap.get(s.getId())));
        list = list.stream().filter(s->StringUtils.isBlank(s.getParentId())).collect(Collectors.toList());
        return list;
    }

    @RequestMapping("/getAllMapList")
    public List<Map<String, Object>> getAllMapList(){
        List<SysPermission> allList = getAllList();
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        for (SysPermission sysPermission : allList) {
            Map<String, Object> resultMap = new HashMap<>();
            setChildList(sysPermission,resultMap);
            resultMapList.add(resultMap);
        }
        return resultMapList;
    }

    private void setChildList(SysPermission sysPermission, Map<String, Object> resultMap) {
        resultMap.put("permissionUrl", sysPermission.getUrl());
        resultMap.put("permissionName", sysPermission.getName());
        List<SysPermission> childrenList = sysPermission.getChildrenList();
        if (CollectionUtils.isNotEmpty(childrenList)){
            List<Map<String, Object>> ChildrenMapList = new ArrayList<>();
            for (SysPermission children : childrenList) {
                Map<String, Object> childrenMap = new HashMap<>();
                setChildList(children, childrenMap);
                ChildrenMapList.add(childrenMap);
            }
            resultMap.put("childrenList", ChildrenMapList);
        }
    }
}

